package com.tms.ned.controlmonitor.adapters;

import java.awt.Component;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JComboBox;

import com.tms.ned.controlmonitor.ComponentChangeEvent;
import com.tms.ned.controlmonitor.validate.Validator;

/*
 * Licensed under the Apache License, Version 2.0;<br> 
 * 
 * You may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless 
 * required by applicable law or agreed to in writing, software distributed under the License 
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and limitations under the License. 
 */


/**
 * A class that adapts JComboBox into something that can be registered with a
 * ControlMonitor.
 *
 * @author bshannon
 *
 */
public class ComboBoxAdapter extends AbstractComponentAdapter  {

	/** The combo being adapted. * */
	private JComboBox combo;

	/** Holds the initial value of the combo box * */
	private Integer initialValue;

	/**
	 * Implementation of the ItemListener, this is the main logic. It adapts an
	 * ItemEvent into a ComponentChangeEvent.
	 */
	private ItemListener internalItemListener = new ItemListener() {
		public void itemStateChanged(ItemEvent e) {
			ComponentChangeEvent event = new ComponentChangeEvent(ComboBoxAdapter.this, ComboBoxAdapter.this);
			fireComponentChangeEvent(event);
		}
	};

	/**
	 * Constructs a ComboComponentAdapter.
	 *
	 * @param name
	 *            The name of the combo.
	 * @param component
	 *            The combo.
	 * @param validator
	 *            The validator for the combo, if any. (can be null).
	 */
	public ComboBoxAdapter(String name, Component component, Validator validator) {
		super(name, component, validator);
		this.combo = (JComboBox) component;
		combo.addItemListener(internalItemListener);
		setInitialValue(Integer.valueOf(combo.getSelectedIndex()));
	}

	/**
	 * Returns the current value (the selected index as an Integer) of the
	 * combo.
	 */
	public final Object getCurrentValue() {
		return Integer.valueOf(combo.getSelectedIndex());
	}

	/**
	 * Returns the initial value of the combo, which is the value of the time
	 * this class started adapting it.
	 */
	public final Object getInitialValue() {
		return Integer.valueOf(initialValue);
	}

	/**
	 * Sets the initial value of the combo. You can use this to override what
	 * the initial value was, thusly affecting dirty checks.
	 */
	protected final void changeInitialValue(Object o) {
		this.initialValue = Integer.valueOf(o + "");
		internalItemListener.itemStateChanged(null);
	}


}
